package com.facebook.drawee.components;

import android.os.Handler;
import android.os.Looper;

import com.facebook.common.internal.Preconditions;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public final class DeferredReleaser {
    public interface Releasable {
        void release();
    }

    public final Set<Releasable> mPendingReleasables;
    public final Handler mUiHandler;
    public final Runnable releaseRunnable = new Runnable() {
        public final void run() {
            DeferredReleaser.this.ensureOnUiThread();
            Iterator<Releasable> iterator = mPendingReleasables.iterator();
            while (iterator.hasNext()) {
                iterator.next().release();
            }
            mPendingReleasables.clear();
        }
    };
    private static DeferredReleaser sInstance = null;

    public DeferredReleaser() {
        this.mPendingReleasables = new HashSet();
        this.mUiHandler = new Handler(Looper.getMainLooper());
    }

    public final void cancelDeferredRelease(Releasable releasable) {
        ensureOnUiThread();
        this.mPendingReleasables.remove(releasable);
    }

    public static DeferredReleaser getInstance() {
        synchronized (DeferredReleaser.class) {
            if (sInstance == null) {
                sInstance = new DeferredReleaser();
            }
        }
        return sInstance;
    }

    public static void ensureOnUiThread() {
        Preconditions.checkState(Looper.getMainLooper().getThread() == Thread.currentThread());
    }
}

